import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:search_people/utils/img_util.dart';

import 'index.dart';

class TrdTouchController extends GetxController
    with GetSingleTickerProviderStateMixin {
  TrdTouchController();

  final state = TrdTouchState();

  void setupOprations() {
    state.oprations = [
      TrdOprationModel(
          name: '打开', url: 'icon_about.png'.imgPathMe, onTap: () {}),
      TrdOprationModel(
          name: '扫一扫', url: 'icon_about.png'.imgPathMe, onTap: () {}),
    ];
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    setupOprations();
    state.animCtrl = AnimationController(
        vsync: this,
        lowerBound: 0.6,
        upperBound: 1.2,
        duration: const Duration(milliseconds: 200))
      ..addListener(() {
        state.scale = state.animCtrl.value;
        if (state.animCtrl.isCompleted) {
          state.isShowBlur = true;
        }
        update();
      });

    var sbottom = MediaQuery.of(Get.context!).padding.bottom;
    state.md = Get.arguments;
    if (state.md != null) {
      var box = state.md?.key.currentContext?.findRenderObject() as RenderBox;
      var offset = box.localToGlobal(Offset(box.size.width, box.size.height));
      state.offset = Offset(offset.dx - Get.width, offset.dy - box.size.height);
      state.size = box.size;

      double op_offx = 0;
      double op_offy = 0;
      if (state.offset!.dx + box.size.width < Get.width - 180.r - 30.r) {
        op_offx = state.offset!.dx + box.size.width;
      } else {
        op_offx = state.offset!.dx;
      }

      op_offx = max(op_offx, 30.r);

      var oprationH = state.oprations.length * 41.r;
      if (state.offset!.dy + box.size.height >
          Get.height - sbottom - 30.r - oprationH) {
        op_offy = state.offset!.dy - oprationH;
      } else {
        op_offy = state.offset!.dy + box.size.height + 20.r;
      }

      state.oprationOffset = Offset(op_offx, op_offy);
    }
  }

  void actionDismiss() {
    state.isShowBlur = false;
    state.animCtrl.animateBack(1).then((value) {
      Get.back();
    });
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
    state.animCtrl.forward();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.animCtrl.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
